<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;

use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Input;
use App\Models\Account\PlayerActModel;
use App\Models\Account\PlayerOnline;
use App\Models\Area;

use App\Admin\Extra\Search\Html;

class PlayerController extends Controller
{

    // 账号列表
    public function anyListAccount()
    {
        $req_param = Input::all();
        PlayerActModel::getAccountByName();
        return Admin::content(function (Content $content)use($req_param) {

            $content->header('player account');
            $content->description('.....');

            $content->row(Html::append([
                Html::input('lastAreaId', 'area choice', '', $req_param['lastAreaId']),
                    Html::likeRedirect('playerName', 'player name', url()->current(), $req_param['playerName']) ,
                    Html::button('GO', url()->current(), 'search-filter'),
                    Html::sjs(url()->current())
                ]));	


            $grid = Admin::grid(PlayerActModel::class, function(Grid $grid){
                // 第一列显示id字段，并将这一列设置为可排序列
                $grid->account('account')->sortable();
                $grid->model()->orderBy('account', 'DESC');

                // 第二列显示title字段，由于title字段名和Grid对象的title方法冲突，所以用Grid的column()方法代替
                $grid->column('lastPlayerId');
                $grid->mainChannel('main channel');

                $area_data = \App\Models\Area::areaSelectData(0);
                $grid->lastAreaId('area')->display(function($value)use($area_data){
                    return $area_data[$value];
                });

                // 第三列显示director字段，通过display($callback)方法设置这一列的显示内容为users表中对应的用户名
                // $grid->director()->display(function($userId) {
                //     return User::find($userId)->name;
                // });

                // 第六列显示released字段，通过display($callback)方法来格式化显示输出
                $grid->identity('user identiy')->display(function ($identity) {
                    $arr = [0 => 'common', 1 => 'special', 2 => 'test', 1000 => 'robot'];
                    return isset($arr[$identity]) ?$arr[$identity] : '--';
                });

                // 下面为三个时间字段的列显示
                $grid->is_seal_number('seal state')->display(function($is_seal_number) {
                    $arr = [1 => 'unsealed', 2 => 'sealed'];
                    return isset($arr[$is_seal_number]) ?$arr[$is_seal_number]: $arr[1];
                });

                // 玩家角色名
                $grid->playerList('player name')->display(function($players){
                    $roles = json_decode($players, true);
                    return implode(' | ', array_column($roles?:[], 'playerName'));
                });

                // 禁用按钮
                $grid->disableCreateButton();

                // filter($callback)方法用来设置表格的简单搜索框
                $grid->filter(function ($filter)use($area_data) {

                    // 模糊查询 注意
                    $filter->where(function($query){
                        $aids = \App\Models\Account\PlayerActModel::getAccountByName('', 'playerName');
                        //var_dump($aids);exit;
                        $query->whereIn('account', $aids?:[]);
                    }, 'player name', 'playerName');

                    $filter->equal('account', 'account')->placeholder('user account');
                    $filter->equal('lastPlayerId', 'player id')->placeholder('player id');

                    $filter->in('mainChannel', 'main channel')->multipleSelect(Area::$area_mc);
                    $filter->equal('lastAreaId', 'area chioce')->select($area_data);

                    // 设置created_at字段的范围查询
                    $filter->between('created_at', 'Created Time')->datetime();

                    //
                    $filter->disableIdFilter();
                });

                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append('<a href="'.url('admin/player/show?accountId='). $actions->row->account .'"><i class="glyphicon glyphicon-eye-open"></i></a>');
                    $actions->append('&nbsp;&nbsp;&nbsp;&nbsp;');
                    $actions->append(Html::button('<span class="glyphicon glyphicon-envelope" aria-hidden="true"></span>', '/admin/mail/create?id=0&area='.$actions->row->lastAreaId.'&receiver='.$actions->row->lastPlayerId, 'btn-goto btn-clear-all'));
                });
            });
            $content->row($grid->render());	
            //$content->body(phpinfo());
        });

    }

    //账号详情 
    public function anyShow(Request $request) {
        $accountId = $request->get('accountId');

        $info = PlayerActModel::detailPlayer($accountId);
        $data = [
            'title_act' => 'account operator',
        ];
        $data = array_merge($data, $info);
        return Admin::content(function (Content $content) use($data){
            $content->header('account manager');
            $content->description('.....');

            $content->row(view('admin.player.player_show', $data?:[]));	

        });
    }

    // 用户操作
    public function ajaxActPlayer(Request $request){
        $exAccount = new \App\Admin\Extra\Player\Account();
        $res = $exAccount->ajaxAct($request);
        return response($res, 200)
            ->header('Content-Type', 'application/json');
    }

    // 管理员添加的 用户体力列表
    public function anyListPower(){
        return Admin::content(function($content){
            $content->header('给玩家赠鸡腿，体力值列表');
            $content->description('.....');

        });

    }

    public function anyAddPower(){
        return Admin::content(function($content){
            $content->header('thew manager');
            $content->description('.....');

            $get = Input::all();

            $form = new Form();
            $form->divide();
            $form->text('playerId', '用户playerid')->rules('required|min:3')->help('请在玩家管理地方搜索到palyerId 再传到这里')->default($get['playerId']?:'');
            $form->text('area', '玩家所在的区域')->help('是玩家所在区域，必选项')->default($get['area']?:'');
            $form->number('thew', '鸡腿数量')->rules('required|min:3');
            $form->hidden('_token', '_token')->default(csrf_token());
            $form->action('/admin/player/api-power');
            // $form->disablePajax();

            $content->row($form);
        });
    }

    // 保存并发送体力给 game server
    public function apiPower(){
        $res = Input::all();
        $playerId = intval($res['playerId']);
        $area = intval($res['area']);
        $thew = intval($res['thew']);

        $playerInfo = \App\Models\Account\PlayerActModel::getPlayerInfo($playerId, $area ?:0);
        $areaInfo = \App\Models\Area::areaInfo($area);

        $data = ['command' => 'proc', 'dataCnt' => 114001100,'dataCnt' => $thew];
        $notify = \App\Models\Account\Thew::orgNotifyData($playerInfo, $data);

        \App\Models\Account\Thew::notifyGame($notify);

        \Log::debug('org notify thew', [$data]);
        $res['code'] = 0;
        return redirect('/admin/home/redirect?code=0&redirect='.url()->to('/admin/').'');
        //return response($res, 200)->header('Content-Type', 'application/json');
    }

    public function testOnlinePlayer()
    {
        $req_param = Input::all();
        PlayerOnline::GetOnlinePlayerList(66);
        return Admin::content(function (Content $content)use($req_param) {

            $content->header('testOnline form');
            $content->description('线上玩家统计');

            $content->row(Html::append([
                Html::input('cp_player_id', 'cp_player_id', url()->current()),
                    Html::button('GO', url()->current(), 'search-filter'),
                    Html::sjs(url()->current())
                ]));


            $grid = Admin::grid(PlayerOnline::class, function(Grid $grid){

                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                });


                $grid->account('account');
                $grid->model()->orderBy('account', 'DESC');


                $grid->column('passwd');
                $grid->column('cmuid');
                $grid->column('mail');
                $grid->column('mobile');
                $grid->column('udid');
                $grid->column('macAddress');
                $grid->column('ua');
                $grid->column('mainChannel');
                $grid->column('secondChannel');
                $grid->column('product');
                $grid->column('identity');
                $grid->column('freeze');
                $grid->column('countries');
                $grid->column('createTime');
                $grid->column('lastLoginTime');
                $grid->column('lastLogoutTime');
                $grid->column('lastAreaId');
                $grid->column('lastPlayerId');
                $grid->column('playerList');
                $grid->column('is_seal_number');
                $grid->column('seal_number_time_limit');

                $grid->filter(function ($filter){

                    $filter->like('account', 'account')->placeholder('');

                });
            });
            $content->row($grid->render());
        });

    }
}

